<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="生产任务单" prop="productionOrderId">
        <el-select v-model="formData.productionOrderId" placeholder="请选择" filterable :disabled="formData.isDisabled"  @change="handleProductionChange()">
        <el-option
            v-for="item in productionOrderList"
            :key="item.id"
            :label="item.serialNumber"
            :value="item.id"
        />
      </el-select>
      </el-form-item> 
      </el-col>
      <el-col :span="8">
      <el-form-item label="业务员" prop="personId">
        <el-select
v-model="formData.personId" placeholder="请选择"  filterable 
              :disabled="formData.isDisabled">
        <el-option
            v-for="item in personList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
      </el-form-item> 
      </el-col>
      <el-col :span="8">
        <el-form-item label="部门" prop="deptId">
        <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id" 
              placeholder="请选择部门"
              filterable 
              :disabled="true"
            />
      </el-form-item>
      </el-col>
    </el-row>


    <el-row :gutter="20">
      <el-col :span="8">
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="formData.warehouseId" placeholder="请选择" filterable :disabled="formData.isDisabled">
        <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>      
          </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="入库日期" prop="orderDate">
        <el-date-picker
          v-model="formData.orderDate"
          type="date"
          value-format="x"
          placeholder="选择入库日期"
          :disabled="formData.isDisabled"
          style="width: 100%;"
        />
      </el-form-item>
      </el-col>
      <el-col :span="8">
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" :disabled="formData.isDisabled" />
      </el-form-item>
      </el-col>
    </el-row>   

    <el-row :gutter="20">

    <el-col :span="8">
      <el-form-item label="流水号" prop="serialNumber">
      <el-input v-model="formData.serialNumber" placeholder="自动生成" :disabled="true"/>
    </el-form-item>
    </el-col>
    <el-col :span="8"/>
    <el-col :span="8"/>

    </el-row>

    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="生产入库子" name="rdrecords10">
        <Rdrecords10Form ref="rdrecords10FormRef" :pid="formData.id" :productionOrderId="formData.productionOrderId"  :isDisabled="formData.isDisabled" />
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <el-button @click="submitForm" type="primary" :isDisabled="formData.isDisabled" :disabled="formLoading|| route.query.type === 'select'" >确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { Rdrecord10Api, Rdrecord10VO } from '@/api/wms/rdrecord10'
import Rdrecords10Form from './components/Rdrecords10Form.vue'
import { useRoute, useRouter } from 'vue-router'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { WarehouseApi, WarehouseVO } from '@/api/wms/warehouse'
import { PersonApi, PersonVO } from '@/api/wms/person'
import { getSimpleDeptList } from '@/api/system/dept';
import { defaultProps, handleTree } from '@/utils/tree';
import { useTagsViewStore } from '@/store/modules/tagsView'
import { ProductionOrderApi, ProductionOrderVO } from '@/api/wms/productionorder'

const { push, currentRoute } = useRouter()
const { delView } = useTagsViewStore() // 视图操作
defineOptions({
    name: 'rdrecord10FormCreate'
})
/** 生产入库主 表单 */
// defineOptions({ name: 'rdrecord10Form' })
const route = useRoute()
const router = useRouter()
const { t } = useI18n() // 国际化
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  serialNumber: undefined,
  personId: undefined,
  deptId: undefined,
  warehouseId: undefined,
  orderDate: new Date().getTime(),
  remark: undefined,
  auditor: undefined,
  auditTime: undefined,
  processInstanceId: undefined,
  status: undefined,
  isDisabled:false,
  productionOrderId:undefined
})
const formRules = reactive({
  productionOrderId: [{ required: true, message: '生产任务单不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],
  orderDate: [{ required: true, message: '订单日期不能为空', trigger: 'blur' }],
  personId: [{ required: true, message: '业务员不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],

})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('rdrecords10')
const rdrecords10FormRef = ref()
const personList = ref([] as PersonVO[]) // 岗位列表
const deptList = ref<Tree[]>([]) // 树形结构
const warehouseList = ref([] as WarehouseVO[]) // 
const productionOrderList = ref([] as ProductionOrderVO[])
//加载数据
onMounted(async () => {
  //加载人员数据
  // personList.value = await PersonApi.getPersonSimpleList()
  //加载部门树
  deptList.value = handleTree(await getSimpleDeptList())
  warehouseList.value= await WarehouseApi.getWarehouseSimpleList()
  productionOrderList.value = await ProductionOrderApi.findProductionOrderOperateList()
  initFormData(route.query.id ? String(route.query.id) : undefined)

})

/** 初始化表单数据 */
const initFormData = async (id?: string) => {
  console.log('初始化'+route.query.id)
  if (id) {
    formLoading.value = true
    try {
      console.log('查询数据')
      formData.value = await Rdrecord10Api.getRdrecord10(id)
      if(route.query.type=='select')
      {
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }else if(route.query.type=='update'){
        formData.value.isDisabled = false; // 修改时可以编辑
      formType.value = 'update';
      }else if(route.query.type=='create'){
      // formData.value.isDisabled = false; // 新增时可以编辑
      formType.value = 'create';
      resetForm();
      }else{
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // resetForm()
    formData.value.isDisabled = false; // 创建时可以编辑

    formType.value = 'create'
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await rdrecords10FormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'rdrecords10'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Rdrecord10VO
    // 拼接子表的数据
    data.rdrecords10s = rdrecords10FormRef.value.getData()
    if (formType.value === 'create') {
      await Rdrecord10Api.createRdrecord10(data)
      ElMessage.success(t('common.createSuccess'))
    } else {
      await Rdrecord10Api.updateRdrecord10(data)
      ElMessage.success(t('common.updateSuccess'))
    }
     delView(unref(currentRoute))
    push('/product/rdrecord10')
  } finally {
    formLoading.value = false
  }
}


/** 返回上一页 */
const goBack = () => {
   delView(unref(currentRoute))
    push('/product/rdrecord10')
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serialNumber: undefined,
    personId: undefined,
    deptId: undefined,
    warehouseId: undefined,
    orderDate: new Date().getTime(),
    remark: undefined,
    auditor: undefined,
    auditTime: undefined,
    processInstanceId: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}

const formDataPomain = ref({

  deptId: undefined,

});

const deptIdData = reactive({
  deptId: undefined,

})

const handleProductionChange = async () => {
  formDataPomain.value = await ProductionOrderApi.getProductionOrder(formData.value.productionOrderId);
    formData.value.deptId =formDataPomain.value.deptId;
    deptIdData.deptId=formData.value.deptId;
   personList.value = await PersonApi.getPersonList(deptIdData);

    
};
</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>